<template>
  <main-card title="模型管理" :show-screen-space="false">
    <template #tool-btn>
      <a-button class="ml-8" type="primary" @click="createModelBase">
        <span class="text">创建模型</span>
      </a-button>
    </template>

    <div class="mb-48 fbc">
      <a-select v-model:value="pageForm.type" class="w-140" :options="typeOptions" @change="getDataList()" />
      <div class="flex-1"></div>
      <g-input
        v-model:value="pageForm.name"
        v-trim
        class="h-36"
        allow-clear
        :search="true"
        placeholder="请输入名称"
        style="width: 328px"
        @keyup.enter="getDataList({ offset: 1 })"
      />
    </div>

    <div class="page-table">
      <a-table
        :columns="tableColumns"
        :data-source="dataList"
        :pagination="false"
        :style="{ width: '100%' }"
        :custom-row="r => ({ onClick: () => openNewPage(r.id) })"
        @change="tableChange"
      >
        <template #bodyCell="{ column, record }">
          <template v-if="column.dataIndex === 'type'">
            <div :class="[record.type && 'type-mark']">
              {{ ALGO_TYPE_OPTIONS.find((item: any) => item.value === record.type)?.label || '/' }}
            </div>
          </template>
          <template v-else-if="column.dataIndex === 'operate'">
            <a-dropdown placement="bottom" @click.stop>
              <a-button :data-share="record?.createType === 1" type="text" class="icon-only-btn" @click.stop>
                <i class="iconfont icon-more-line"></i>
              </a-button>
              <template #overlay v-if="checkPermissions(record?.createType, record?.readOnly)">
                <a-menu>
                  <a-menu-item
                    v-if="checkPermissions(record?.createType, record?.readOnly)"
                    class="menu-icon-item"
                    @click="clickList({ ...record, title: '重命名', okBtn: '确定' })"
                  >
                    重命名
                  </a-menu-item>
                  <a-menu-item
                    v-if="checkPermissions(record?.createType, record?.readOnly)"
                    class="menu-icon-item"
                    @click="clickList({ ...record, title: '新增版本', okBtn: '确定' })"
                  >
                    新增版本
                  </a-menu-item>
                  <a-menu-item
                    v-if="checkPermissions(record?.createType, record?.readOnly)"
                    class="menu-icon-item"
                    @click="clickList({ ...record, title: '确认删除', okBtn: '删除' })"
                  >
                    删除
                  </a-menu-item>
                  <!-- <a-menu-item class="menu-icon-item" @click="handleToDownload(record)"> 下载 </a-menu-item> -->
                  <a-menu-item
                    v-if="checkPermissions(record?.createType, record?.readOnly)"
                    class="menu-icon-item"
                    @click="handleOpenShareModal(record)"
                  >
                    分享
                  </a-menu-item>
                </a-menu>
              </template>
            </a-dropdown>
          </template>
        </template>
      </a-table>
    </div>

    <g-pagination v-model:offset="pageForm.offset" v-model:limit="pageForm.limit" :total="pageForm.total" @change="getDataList" />

    <a-modal
      v-model:open="visibleModal"
      centered
      width="416px"
      :title="modalTitle"
      :mask-closable="false"
      :body-style="{ 'padding-bottom': '0' }"
      :ok-text="okText"
      :ok-button-props="{ loading, disabled: okButton }"
      :confirm-loading="confirmLoading"
      @ok="handleOk"
      @cancel="resetForm"
    >
      <a-spin :spinning="isLoading" tip="加载中">
        <div v-if="modalTitle === '创建模型'">
          <a-form ref="formRef" :model="formState" name="basic" layout="vertical" class="my-a-form" :rules="rules">
            <div class="on-line-two-item">
              <a-form-item :label="`${clickOnType}名称`" name="name">
                <g-input
                  v-model:value="formState.name"
                  :search="false"
                  :maxlength="200"
                  placeholder="请输入模型名称"
                  @input="confirmDeletion"
                />
              </a-form-item>
              <a-form-item :label="`${clickOnType}类型`" name="type" :rules="[{ required: true, message: `请选择${clickOnType}类型` }]">
                <a-select v-model:value="formState.type" :options="ALGO_TYPE_OPTIONS" :placeholder="`请选择${clickOnType}类型`" />
              </a-form-item>
            </div>
          </a-form>
        </div>
        <div v-if="modalTitle === '重命名'">
          <a-form ref="formRef" :model="formState" name="basic" layout="vertical" class="my-a-form" :rules="rules">
            <div class="on-line-two-item">
              <a-form-item :label="`${clickOnType}名称`" name="name">
                <g-input
                  v-model:value="formState.name"
                  :search="false"
                  :maxlength="200"
                  placeholder="请输入模型名称"
                  @input="confirmDeletion"
                />
              </a-form-item>
            </div>
          </a-form>
        </div>
      </a-spin>
    </a-modal>
  </main-card>

  <delete-confirm-dialog
    v-model:show="isDeleteDialogShow"
    :msg="`此${clickOnType}及其所有版本将被删除，不可恢复，请确认操作`"
    :label="`请输入模型名称`"
    :loading="confirmLoading"
    :confirm-name="delDataGroupName"
    @ok="onOkDeleteTask"
  />

  <share-modal
    ref="shareModalRef"
    :submit-api="modelLibraryApi.share"
    :remove-user-api="modelLibraryApi.removeShareUser"
    :get-list-api="modelLibraryApi.getShareList"
  />

  <addVersionModal ref="addVersionModalRef" :after-close-fn="getDataList" />
</template>
<script setup lang="ts">
  import type { FormInstance, TableProps } from 'ant-design-vue'
  import { message } from 'ant-design-vue'
  import type { Rule } from 'ant-design-vue/es/form'
  import { debounce, storage } from 'g6-fn'
  import { ref } from 'vue'

  // import manualMessage from '@/components/ManualMessage'
  import ShareModal from '@/components/ShareModal/index.vue'
  import useList from '@/hooks/use-list'
  import { modelLibraryApi } from '@/services/api'
  import { validateDirName } from '@/utils'
  import { countStrToBit } from '@/utils'
  // import { waitLoading } from '@/utils'
  import { filterTableColumns } from '@/utils/ant-component'
  import { checkPermissions } from '@/utils/share'

  import { ALGO_TYPE_OPTIONS } from '../../algo-dev/options'
  import addVersionModal from './components/addVersionModal.vue'

  // 类型
  const typeOptions = ref([
    {
      label: '全部类型',
      value: ''
    },
    ...ALGO_TYPE_OPTIONS
  ])

  interface FormState {
    name: string
    type?: number
  }

  type TaskItem = {
    updateTime: null | string
    createTime: string
    id: string
    versionNum: string
    status: string
    name: string
  }

  interface PageForm {
    name: string
    type: string
    status: string
    order: 'desc' | 'asc'
    columns: 'createTime' | ''
    limit: number
    offset: number
  }

  let visibleModal = ref<boolean>(false)
  let modalTitle = ref<string>('创建模型')
  let okText = ref<string>('创建')
  const okButton = ref<boolean>(false)
  const formRef = ref<FormInstance>()
  const datasetId = ref<string>('') //模型ID
  const formState = ref<FormState>({
    name: ''
  })

  const isLoading = ref<boolean>(false)

  const clickOnType = ref<string>('模型')

  const delDataGroupName = ref<string>('')

  const createModelBase = () => {
    visibleModal.value = true
    modalTitle.value = '创建模型'
    formState.value = {
      name: ''
    }
  }

  const handleOk = debounce(async () => {
    // 验证表单
    await formRef.value?.validateFields()
    // 从表单状态中获取数据组名称
    const { name } = formState.value
    // 获取数据集ID
    const id = datasetId.value
    loading.value = true

    if (modalTitle.value === '重命名') {
      handleRequest(modelLibraryApi.renameMyModel({ name: name, id }, { isAddUid: true }), '编辑成功')
    } else if (modalTitle.value === '创建模型') {
      handleRequest(modelLibraryApi.addMyModel(formState.value, { isAddUid: true }), '添加成功')
    }
  }, 500)

  const isDeleteDialogShow = ref(false)
  const onOkDeleteTask = () => {
    const id = datasetId.value
    handleRequest(modelLibraryApi.delMyModel(id)({}, { isAddUid: true }), '删除成功')
  }

  const addVersionModalRef = ref()
  const clickList = (e: any) => {
    modalTitle.value = e.title
    delDataGroupName.value = e.name
    datasetId.value = e.id
    if (e.title === '确认删除') {
      isDeleteDialogShow.value = true
      return
    }
    if (e.title === '新增版本') {
      console.log('操作对象', e)
      addVersionModalRef.value?.open(e.id, e.url)
      return
    }
    visibleModal.value = true
    okText.value = e.okBtn
    formState.value.name = e.title !== '确认删除' ? e.name : ''
  }

  const confirmLoading = ref(false)
  const handleRequest = async (requestFunc: Promise<any>, successMessage: string) => {
    try {
      confirmLoading.value = true
      await requestFunc
      message.success(successMessage)
      getDataList()
      resetForm()
      isDeleteDialogShow.value = false
    } finally {
      loading.value = false
      confirmLoading.value = false
    }
  }

  const resetForm = () => {
    visibleModal.value = false
    datasetId.value = ''
    modalTitle.value = ''
    okButton.value = false
    okText.value = '确定'
    formState.value = {
      name: ''
    }
    formRef.value?.resetFields()
  }

  const validateByte = async (rule: Rule, value: string) => {
    const byteCount = countStrToBit(value)
    if (byteCount > 200) {
      return Promise.reject('名称不可超过200字节')
    }
    return Promise.resolve()
  }
  const rules: Record<string, Rule[]> = {
    name: [
      { required: true, message: '请输入模型名称' },
      { validator: validateDirName() },
      {
        validator: validateByte
      }
    ]
  }

  const confirmDeletion = (): void => {
    if (modalTitle.value === '确认删除') {
      if (formState.value.name === delDataGroupName.value) {
        okButton.value = false
      } else {
        okButton.value = true
      }
    }
  }

  /*----------------------------------------- 分享 --------------------------------*/
  const shareModalRef = ref<InstanceType<typeof ShareModal>>()
  const handleOpenShareModal = (item: any) => {
    shareModalRef.value?.open({
      id: item.id
    })
  }

  const openNewPage = (id: string) => {
    // 构建包含查询参数的 URL
    const url = `/my-model-manage/detail/${id}`
    // 在新标签页或窗口中打开页面
    window.open(url, '_blank')
  }

  type TableDataType = {
    key: string
    name: string
    age: number
    address: string
  }

  // 表格
  const tableColumns = ref(
    filterTableColumns([
      {
        title: '名称',
        dataIndex: 'name',
        width: 240
      },
      {
        title: '标签',
        dataIndex: 'type',
        width: 240
      },
      {
        title: '版本数量',
        dataIndex: 'versionNum',
        width: 240,
        isSort: true
      },
      {
        title: '创建时间',
        dataIndex: 'createTime',
        width: 190,
        isSort: true
      },
      {
        title: '操作',
        width: 80,
        dataIndex: 'operate'
      }
    ])
  )

  const { pageForm, dataList, loading, getDataList } = useList<PageForm, TaskItem>(modelLibraryApi.myModelList, {
    name: '',
    status: '',
    type: '',
    columns: 'createTime',
    order: 'desc',
    limit: 10,
    offset: 1
  })

  // 表格变化
  const tableChange: TableProps<TableDataType>['onChange'] = (pagination, filters, sorter: any) => {
    pageForm.value.order = sorter.order === 'ascend' ? 'asc' : 'desc'
    pageForm.value.columns = sorter.field
    if (!sorter.order) {
      pageForm.value.columns = 'createTime'
      pageForm.value.order = 'desc'
    }
    getDataList({ offset: 1 })
  }
  getDataList()

  //检查uploadingFileId并进行处理
  const checkTheUploadList = async (): Promise<void> => {
    // 检查 localStorage 中是否存在 'uploadModelFile' 这个键
    const storedParams = storage.get('uploadModelFile')
    console.log(storedParams, '000')

    if (storedParams) {
      try {
        const params = storedParams
        console.log(params, 'storedParams')
        // 调用后端的上传完成接口
        const { code, data } = await modelLibraryApi.deleteNotUploaded(params, {
          isAddUid: true
          // data: params
        })

        if (code === 'SYSTEM-100000' && data) {
          storage.remove('uploadModelFile')
          console.log('删除成功')
        }
        //
      } catch (error) {}
    }
  }

  checkTheUploadList()
</script>
<style lang="less" scoped>
  .type-mark {
    display: inline-block;
    padding: 3px 6px;
    color: #4686ed;
    background: #f2f6fe;
    border: 1px solid @mask1;
    border-radius: 6px;
    line-height: 22px;
  }

  .card-content {
    display: grid;
    width: 100%;
    gap: 20px;
    row-gap: 24px;
    grid-template-columns: repeat(auto-fill, minmax(329px, 1fr));
  }

  .infinite-box {
    display: flex;
    justify-content: center;
    width: 1376px;
  }

  .tips {
    display: flex;
    margin-bottom: 30px;
    font-size: 14px;
    color: rgba(0, 0, 0, 0.75);
    line-height: 24px;

    .icon {
      margin-right: 10px;
      font-size: 24px;
      color: #f59700;

      i {
        font-size: 24px;
      }
    }
  }

  .delConfirmation {
    margin-bottom: 7px;
    font-size: 14px;
    line-height: 22px;
    color: rgba(25, 25, 48, 0.45);

    .modelName {
      color: rgba(0, 0, 0, 0.75);
    }
  }

  :deep(.ant-modal-footer) {
    padding-top: 44px;
  }
</style>
../types ./options
